import { uploadJsonFile } from 'mapFileWrapper'
import { promiseSpriteFrame } from 'imageWrapper'
import { BLOCK_TYPE, } from 'constant'

cc.Class({
    extends: cc.Component,

    properties: {
        mapBlock: cc.Prefab,
    },

    onLoad() {
        cc.director.getPhysicsManager().enabled = true // 开启物理系统
        cc.director.getCollisionManager().enabled = true // 开启普通碰撞检测
        // cc.director.getCollisionManager().enabledDebugDraw = true
        cc.debug.setDisplayStats(false)

        let scene = cc.director.getScene()
        this.canvas = scene.getChildByName('Canvas')
        this.playerController = this.node.getComponent('playerController')
        this.mapLayer = this.canvas.getChildByName('mapLayer')
        this.cameraNode = this.canvas.getChildByName('Main Camera')
        this.uiLayer = this.canvas.getChildByName('uiLayer')

        this.mapData = {}
    },

    start() {

    },

    // 清空地图
    clearMapView() {
        let blockLayer = this.mapLayer.getChildByName('blockLayer')
        blockLayer.removeAllChildren()
    },

    // 在地图上创建一个块
    createBlockOnView(config) {
        let imageUrl = config.path
        let block = cc.instantiate(this.mapBlock)

        block.parent = this.mapLayer.getChildByName('blockLayer')
        block.blockType = config.type
        block.width = config.width || 100
        block.height = config.height || 100
        block.angle = config.angle || 0

        block.blockId = config.blockId // 这样命名是为了不和节点本身的属性命名冲突
        block.blockName = config.blockName
        block.blockComponents = config.blockComponents

        block.setPosition(config.position)
        promiseSpriteFrame(imageUrl, block)
            .then(() => {

                if (block.blockType == BLOCK_TYPE.CHARACTER) {
                    this.initPlayer(block)
                } else {
                    this.parseComponent(block)

                }
            })

        return block
    },

    // 解析组件
    parseComponent(blockNode) {
        let componentsArray = blockNode.blockComponents
        for (let component of componentsArray) {
            blockNode.addComponent(component)
        }
    },

    initPlayer(block) {
        let rigidBody = block.addComponent(cc.RigidBody)
        let boxCollider = block.addComponent(cc.PhysicsBoxCollider)
        let playerProperty = this.mapData.playerProperty

        boxCollider.editing = true
        boxCollider.size.height = block.height
        boxCollider.size.width = block.width
        boxCollider.apply()

        rigidBody.gravityScale = 2 // playerProperty.gravity
        rigidBody.fixedRotation = true
        boxCollider.friction = 0
        // this.playerController.horizontalSpeed = playerProperty.horizontalSpeed
        // this.playerController.verticalSpeed = playerProperty.verticalSpeed
        this.playerController.player = block
        block.addComponent('addBoxCollider')

        block.zIndex = 9999
        console.log(this.playerController.player)
    },

    // 渲染地图
    renderBlocks() {
        let blockData = this.mapData.blocks
        for (let i = 0; i < blockData.length; i++) {
            let d = blockData[i]
            this.createBlockOnView(d)
        }
    },

    // 加载编辑器场景
    btn_LoadEditor() {
        cc.director.loadScene("edit")
    },

    // 读取地图
    btn_ReadMap() {
        uploadJsonFile().then(mapString => {
            this.clearMapView()
            this.mapData = JSON.parse(mapString)
            this.renderBlocks()
            this.gameInit()
        })
    },

    // 游戏初始化
    gameInit() {
        // let followAction = cc.follow(this.playerController.player)
        // this.cameraNode.runAction(followAction)
    },

    // ui 层跟随摄像机
    uiLayerFollowCamera() {
        this.uiLayer.x = this.cameraNode.x
        this.uiLayer.y = this.cameraNode.y
    },

    // 更新摄像机位置
    updateCamera() {
        if (!this.playerController.player) {
            return
        }
        // 将玩家的坐标映射到相机坐标域， 定义上下左右边界， 如果玩家在边界内就什么都不做， 如果玩家在边界值外相机就跟随玩家
        let rect = {
            top: 200,
            down: 200,
            right: 200,
            left: 200
        }
        let player = this.playerController.player
        let camera = this.cameraNode
        let playerWorldPosition = player.parent.convertToWorldSpaceAR(player.getPosition())
        let cameraWorldPosition = camera.parent.convertToWorldSpaceAR(camera.getPosition())
        let playerToCameraParentPosition = camera.parent.convertToNodeSpaceAR(playerWorldPosition)

        if (playerWorldPosition.x < cameraWorldPosition.x - rect.right) {
            camera.x = playerToCameraParentPosition.x + rect.right
        }

        if (playerWorldPosition.x > cameraWorldPosition.x + rect.left) {
            camera.x = playerToCameraParentPosition.x - rect.left
        }

        if (playerWorldPosition.y < cameraWorldPosition.y - rect.down) {
            camera.y = playerToCameraParentPosition.y + rect.down
        }

        if (playerWorldPosition.y > cameraWorldPosition.y + rect.top) {
            camera.y = playerToCameraParentPosition.y - rect.top
        }

    },

    update(dt) {
        this.updateCamera()
        this.uiLayerFollowCamera()
    },
});
